package com.zpy.SmartChargeStation.mqtt.client.api;

import com.zpy.SmartChargeStation.mqtt.client.conf.MqttProps;
import com.zpy.SmartChargeStation.mqtt.client.service.MqttService;
import com.zpy.SmartChargeStation.mqtt.client.utils.TransformerUtils;
import com.zpy.SmartChargeStation.protocol.mqtt.message.ChargePayload;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * description: 发送消息API
 */

@RestController
@Slf4j
public class SendApi {

    @Resource
    private MqttProps props;

    @Resource
    private MqttService gateWay;

    /**
     * description: 发送MQTT消息(payload)
     */
    @RequestMapping(path = "/mqtt/send", method = RequestMethod.POST)
    String doSend(@RequestBody ChargePayload message) {

        //将ChargePayload转换为16进制字符串
        String hex = TransformerUtils.objectToHex(message);
        //将16进制的字符串转换为字节数组
        byte[] bytes = TransformerUtils.hexStringToByteArray(hex);

        Message<byte[]> bytesArray =  MessageBuilder.withPayload(bytes).build();

        //MQTT发送16进制报文
        gateWay.send(props.getTopic(),bytesArray);
        //gateWay.send(props.getTopic(),message);

        return "send mqtt message success !";
    }
}
